import React from 'react';
import { Table, Input, Popconfirm, Icon, Button, message } from 'antd';
import cn from 'classnames';

import { getRankDimensions } from '@/pages/JobRank/service';
import Selector from './Selector';
import styles from './Dimension.less';

let rowKey;
const Dimension = props => {
    const defaultValue = [
        {
            dimensionTypeCode: undefined,
            dimensionTypeName: undefined,
            demand: undefined
        }
    ];
    const { value = defaultValue, onChange, readOnly } = props;

    // 所有下拉项，接口拉取后固定，不做动态
    const [options, setOptions] = React.useState([]);

    React.useEffect(() => {
        // 初始化id
        const fetchData = async () => {
            // const result = await dictionaryList({ code: 'dimensionType' });
            const result = await getRankDimensions();
            if (result.code === 10000) {
                setOptions(result.data.map(item => ({ label: item.dimensionTypeName, value: item.dimensionTypeCode })));
            }
        };
        fetchData();
    }, []);

    // 初始化已有数据的id
    const dataSource = value.length ? value.map((item, index) => ({ id: index, ...item })) : [];

    // 初始的rowKey，在保存的情况下存在没有dimensionValue的情况
    const getInitialId = () => {
        if (!dataSource.length) return 0;
        return Math.max(...dataSource.map(item => Number(item.id)));
    };

    // 生成动态table的id
    const generateId = () => {
        if (rowKey === undefined) rowKey = getInitialId();
        rowKey += 1;
        return rowKey;
    };

    // 删除
    const handleDelete = key => {
        onChange(dataSource.filter(item => item.id !== key));
    };

    // 添加一列
    const handleAdd = () => {
        onChange([
            ...value,
            {
                id: generateId()
            }
        ]);
    };

    // 更新整个组件的value
    const replaceValue = (replacement, matchIndex) => {
        const exist = dataSource[matchIndex];
        onChange([
            ...dataSource.slice(0, matchIndex),
            { ...exist, ...replacement },
            ...dataSource.slice(matchIndex + 1)
        ]);
    };

    // 更新 要求列
    const handleDemandChange = (e, id) => {
        const inputValue = e.target.value;
        const matchIndex = dataSource.findIndex(item => item.id === id);
        if (matchIndex < 0) return;
        const replacement = { demand: inputValue };
        replaceValue(replacement, matchIndex);
    };

    // 更新 维度列
    const handleDimensionChange = ({ id, val }) => {
        const matchIndex = dataSource.findIndex(item => item.id === id);
        if (matchIndex < 0) return;
        // 当修改的维度已经存在时
        const isExist = dataSource.some(item => item.dimensionTypeCode === val);
        if (isExist) {
            message.error('该维度已经存在');
            return;
        }
        // 获取option对应的name，冗余
        const matchOption = options.find(item => item.value === val);
        const matchName = matchOption ? matchOption.label : '';
        // matchName为空时判断为新增维度
        // 新增维度的文字已经存在时
        if (!matchName) {
            const isExistName = dataSource.some(item => item.dimensionTypeName === val);
            if (isExistName) {
                message.error('新增的维度名已经存在');
                return;
            }
        }
        const replacement = { dimensionTypeCode: matchName ? val : '', dimensionTypeName: matchName || val };
        replaceValue(replacement, matchIndex);
    };

    const demandValidator = text => text && text.length <= 200;

    const columns = [
        {
            title: '维度',
            dataIndex: 'dimensionTypeCode',
            render: (text, record) => (
                <div
                    className={cn({
                        [styles.success]: record.dimensionTypeCode || record.dimensionTypeName
                    })}
                >
                    <Selector
                        options={options}
                        value={record.dimensionTypeCode || record.dimensionTypeName} // 新增的维度可以直接展示名字
                        id={record.id}
                        onChange={handleDimensionChange}
                        disabled={readOnly}
                        getPopupContainer={trigger => trigger.parentElement}
                    />
                </div>
            )
        },
        {
            title: '要求',
            dataIndex: 'demand',
            render: (text, record) => (
                <div
                    className={cn({
                        [styles.success]: demandValidator(text)
                    })}
                >
                    <Input
                        placeholder="请输入要求"
                        value={text}
                        onChange={e => handleDemandChange(e, record.id)}
                        disabled={readOnly}
                        maxLength={200}
                    />
                </div>
            )
        },
        {
            title: '操作',
            dataIndex: 'dimensionTypeName',
            render: (text, record) => {
                if (value.length > 1 && !readOnly) {
                    return (
                        <Popconfirm title="确认删除？" onConfirm={() => handleDelete(record.id)}>
                            <a href="#" onClick={e => e.preventDefault()}>
                                删除
                            </a>
                        </Popconfirm>
                    );
                }
                return null;
            }
        }
    ];

    return (
        <>
            <Table
                style={{ marginTop: -6 }} // wtf
                rowKey="dimensionTypeCode"
                dataSource={dataSource}
                columns={columns}
                pagination={false}
            />
            {!readOnly && (
                <Button
                    onClick={() => handleAdd()}
                    type="dashed"
                    block
                    style={{
                        marginTop: 16
                    }}
                >
                    <Icon type="plus" /> 添加
                </Button>
            )}
        </>
    );
};

export default Dimension;
